<?php
hd_core::load_class('init', 'school');
class weixin_control extends init_control {
	public function _initialize() {
            parent::_initialize();	
            $this->setting_service = model('admin/setting','service');
            $this->token = Token;
            $this->AppId = AppId;
            $this->AppSecret = AppSecret;	
            $this->weixin_service = $this->load->service('weixin/weixin');
            $this->member_service = $this->load->service('member/member');
	}
	
	public function index(){
		if(strtolower($_SERVER['REQUEST_METHOD']) == 'get') {
			exit( $_GET['echostr'] );
		}

		if(strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
			$this->weixin_service->content($GLOBALS["HTTP_RAW_POST_DATA"]);
		}	
	}
	
	private function checkSignature(){
		$signature = $_GET["signature"];
		$timestamp = intval($_GET["timestamp"]);
		$nonce = intval($_GET["nonce"]); 
		$echostr = $_GET['echostr'];
		$tmpArr = array($this->token, $timestamp, $nonce);
		sort ( $tmpArr, SORT_STRING );
		$tmpStr = implode ( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		if ($tmpStr == $signature) {
			echo $echostr;
		}
	}

	public function aouth(){
		$codes=$this->weixin_service->get_token($_GET['code']);
		if($codes['access_token']==''){
			echo "授权失败1!";exit;
		}
		$info = $this->weixin_service->get_info($codes['access_token'],$codes['openid']);
		
		$data['unionid'] = $codes['unionid'];
		$data['openid'] = $codes['openid'];
		$data['username'] = $info['nickname'];
		$data['portrait'] = $info['headimgurl'];
		$data['subscribe'] = 1;
		$data['subscribe_time'] = time();
		$data['token'] = $this->token;
		$data['sex'] = $info['sex'];
		$data['store_id'] = intval($_GET['store_id']);
		$result = $this->member_service->aouth($data);	
		if($result){
			$url = $_GET['url_forward'] ? urldecode($_GET['url_forward']) : url('member/index/index');
			redirect($url);
		}            
	}
}